package com.wh.shiroswagger.filter;

import com.alibaba.fastjson.JSONObject;
import com.wh.shiroswagger.constant.Contant;
import com.wh.shiroswagger.exception.BusinessException;
import com.wh.shiroswagger.result.DataResult;
import com.wh.shiroswagger.result.ResponseCodeMsg;
import com.wh.shiroswagger.token.MyToken;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.springframework.http.MediaType;
import org.springframework.util.StringUtils;

import javax.servlet.ServletOutputStream;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Auther: HuiEr
 * @Date: 2020/3/6 8:53
 * @Description
 */
public class CustomFilter extends AccessControlFilter {
    @Override
    protected boolean isAccessAllowed(ServletRequest servletRequest, ServletResponse servletResponse, Object o) throws Exception {
        return false;
    }

    @Override
    protected boolean onAccessDenied(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {
        HttpServletRequest request=(HttpServletRequest)servletRequest;
        String headerToken = request.getHeader(Contant.REQ_TOKE);
        try{
            if (StringUtils.isEmpty(headerToken)){
            throw new BusinessException(ResponseCodeMsg.TOKEN_NULL.getCode(),ResponseCodeMsg.TOKEN_NULL.getMsg());
        }else{
            MyToken myToken = new MyToken(headerToken);
            getSubject(servletRequest,servletResponse).login(myToken);
        }
        }catch (BusinessException e){
            filterResponse(e.getExcode(), e.getExmsg(),servletResponse);
            return false;
        }catch (AuthenticationException e){
           filterResponse(ResponseCodeMsg.TOKEN_NOTFOUND.getCode(),ResponseCodeMsg.TOKEN_NOTFOUND.getMsg(),servletResponse);
           return false;
        }
        return true;
    }

    private void filterResponse(int code,String msg,ServletResponse servletResponse){
        HttpServletResponse response=(HttpServletResponse)servletResponse;
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code",code);
        jsonObject.put("msg",msg);
        response.setContentType(MediaType.APPLICATION_JSON_UTF8.toString());

        try {
            ServletOutputStream outputStream = response.getOutputStream();
            outputStream.write(jsonObject.toString().getBytes());
            outputStream.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
